<?php

/*
 * Copyright (C) 2014 Administrator.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

class Wdmin extends Controller {

    const LIST_LIMIT = 25;
    const loginKeyK = '4s5mpxa';

    public function __construct($ControllerName, $Action, $QueryString) {
        parent::__construct($ControllerName, $Action, $QueryString);
        $this->loadModel('Db');
    }

    public function index() {
        $this->loadModel('Secure');

//        $this->loadModel('WechatSdk');
//        
//        $slist = WechatSdk::getWechatSubscriberList(WechatSdk::getServiceAccessToken());
//        
//        foreach($slist['data']['openid'] as $sob){
//            $this->Db->query("INSERT INTO wechat_subscribe_record (openid,date,dv) VALUES ('$sob','0000-00-00',1);");
//        }
//        
        // login passK
        if (isset($_COOKIE['loginKey'])) {
            $loginKey = $_COOKIE['loginKey'];
            $Key = $this->Secure->DesDecrypt($loginKey, self::loginKeyK);

            $QueryDate = date("Y-m-d");
            $QueryMonth = date("Y-m");
            $DaySaleData = $this->Db->query("SELECT * FROM `vStatDaySaleSumRaw` WHERE `day` = '$QueryDate';");
            $MonthSaleData = $this->Db->query("SELECT * FROM `vStatMonthSaleSumRaw` WHERE `month` = '$QueryMonth';");

            // 微信关注
            $wechatSub = $this->Db->query("SELECT SUM(dv) AS sc FROM `wechat_subscribe_record`;");

            $this->Smarty->assign('daysale', $DaySaleData[0]);
            $this->Smarty->assign('monthsale', $MonthSaleData[0]);
            $this->Smarty->assign('wechatSub', $wechatSub[0]['sc']);
            $this->Smarty->assign('expressCompany', include dirname(__FILE__) . '/../config/express_code.php');
        } else {
            header('Location:?/Wdmin/login');
            exit(0);
        }

        $this->show();
    }

    /**
     * genLoginQrcode
     * @return type
     */
    private function genLoginQrcode() {
        $ip = $this->getIp();
        // get token
        $loginCode = $this->Db->query("INSERT INTO `admin_login_code_token` (`ip`,`createtime`) VALUES ('$ip',NOW());");
        if ($loginCode == false) {
            $loginCode = $this->Db->query("SELECT tid FROM `admin_login_code_token` WHERE `ip` = '$ip';");
            $this->Db->query("UPDATE `admin_login_code_token` SET `used` = 0 WHERE `ip` = '$ip';");
            $loginCode = $loginCode[0]['tid'];
        }
        // 8814 mask
        $loginCode = '8814' . $loginCode;
        $stoken = WechatSdk::getServiceAccessToken();
        $qrcodeImage = WechatSdk::getCQrcodeImage(WechatSdk::getCQrcodeTicket($stoken, $loginCode, WechatSdk::QR_SCENE));
        return $qrcodeImage;
    }

    /**
     * ajax check login code scan status
     * perform++
     */
    public function checkLogin($Query) {
        $ip = $Query->qco;
        $rst = $this->Db->query("SELECT `used`,`bind` FROM " . TABLE_WDMIN_LOGIN_TOKEN . " WHERE `ip` = '$ip';");
        $status = $rst[0]['used'];
        if ($status == 0) {
            // wait 1.5s
            usleep(1500000);
            echo $status;
        } else {
            $this->loadModel('Secure');
            // scan success
            $loginKey = $rst[0]['bind'];
            $loginKey = $this->Secure->DesEncrypt($loginKey, self::loginKeyK);
            $this->echoJson(array('s' => $status, 'loginKey' => $loginKey));
        }
    }

    /**
     * login page
     */
    public function login() {
        $this->loadModel('WechatSdk');
        $this->Smarty->assign('qrcode', $this->genLoginQrcode());
        $this->Smarty->assign('ip', $this->getIp());
        $this->show();
    }

    /**
     * ajaxLoadOrderlist
     */
    public function ajaxLoadOrderlist($Query) {
        !isset($Query->page) && $Query->page = 0;
        !isset($Query->status) && $Query->status = 'payed';

        $_SQL_limit = $Query->page * self::LIST_LIMIT . "," . self::LIST_LIMIT;

        $orderList = $this->Db->query(sprintf("SELECT * FROM `orders` WHERE status = '%s' ORDER BY `order_time` DESC LIMIT $_SQL_limit;", $Query->status));

        foreach ($orderList as $index => $order) {
            // address
            $address = $this->Db->query("SELECT * FROM `orders_address` WHERE order_id = $order[order_id];");
            $orderList[$index]['address'] = $address[0];
            // product info
            $orderList[$index]['data'] = $this->Db->query("SELECT catimg,`pi`.product_name,`pi`.product_id,`sd`.product_count,`sd`.product_discount_price FROM `orders_detail` sd LEFT JOIN `vProductInfo` pi on pi.product_id = sd.product_id WHERE `sd`.order_id = " . $order['order_id']);
        }

        $this->Smarty->assign('orderlist', $orderList);
        $this->show();
    }

    /**
     * ajaxGetOrderCount
     */
    public function ajaxGetOrderCount() {
        $count = $this->Db->query('SELECT COUNT(*) AS `count` FROM `orders` WHERE `status` = "payed";');
        echo $count[0]['count'];
    }

    /**
     * ajaxGetPageViewData
     * @return json string
     */
    public function ajaxGetPageViewData() {
        $data = $this->Db->query("SELECT
	COUNT(id) AS count,
	DATE_FORMAT(time, '%H') AS dt
FROM
	pageview_records
WHERE
	to_days(time) = to_days(now())
GROUP BY
	DATE_FORMAT(time, '%H') ORDER BY time DESC;");
        $dataX = range(0, 23);
        
        foreach($dataX as $index){
            $dataY[$index] = 0;
        }
        
        foreach ($data as $d) {
            $dataY[(int)$d['dt']] = (int) $d['count'];
        }
        
        // 访问量
        $monthStat = $this->Db->query("SELECT COUNT(*) AS count FROM pageview_records WHERE DATE_FORMAT(time,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m');");
        $dayStat = $this->Db->query("SELECT COUNT(*) AS count FROM pageview_records WHERE to_days(time) = to_days(now());");
        
        $this->echoJson(array(
            'x' => $dataX,
            'y' => $dataY,
            'montot' => $monthStat[0]['count'],
            'daytot' => $dayStat[0]['count']
        ));
    }

    /**
     * ajaxLoadSaleHisCartData
     * 获取报表 单日销售记录
     * @return json string
     */
    public function ajaxLoadSaleHisCartData() {
        $QueryMonth = date("Y-m");
        $data = $this->Db->query("SELECT * FROM `vStatDaySaleSumRaw` WHERE DATE_FORMAT(`day`,'%Y-%m') = '$QueryMonth' ORDER BY `day` DESC;");
        # var_dump($data);
        $dataX = array();
        $dataY = array();
        foreach ($data as $d) {
            $dataY[] = (float) $d['sum'];
            $dataX[] = $d['day'];
        }

        $dataX = array_reverse($dataX);
        $dataY = array_reverse($dataY);

        $this->echoJson(array(
            'x' => $dataX,
            'y' => $dataY
        ));
    }

}
